package com.ry.framework.shiro.filter;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/**
 * 自定义 拦截未登录请求，不适用shiro自带的loginUrl
 * @author Szj
 *
 */
public class AuthenticationFilter extends FormAuthenticationFilter {

	private static final Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class);

    public AuthenticationFilter() {
        super();
    }

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //Always return true if the request's method is OPTIONS
        if (request instanceof HttpServletRequest) {
            if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
                return true;
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String token = getRequestToken((HttpServletRequest) request);
    	if(token == null || "".equals(token)) {
    		HttpServletRequest req = (HttpServletRequest) request;
    		String origin = req.getHeader("Origin");
    		HttpServletResponse res = (HttpServletResponse)response;
    		res.setHeader("Access-Control-Allow-Credentials", "true");
	        res.setHeader("Access-Control-Allow-Origin", origin);
	        res.setStatus(HttpServletResponse.SC_OK);
	        res.setCharacterEncoding("UTF-8");

	        Map<String, Object> map= new HashMap<>();
	        map.put("code", 702);
	        map.put("msg", "未登录");
	        res.getWriter().printf(JSON.toJSONString(map));
	        return false;
    	}
    	return executeLogin(request, response);
    }
	
    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest){
        //从header中获取token
        String token = httpRequest.getHeader("token");

        //如果header中不存在token，则从参数中获取token
        if(token != null && !"".equals(token)){
            token = httpRequest.getParameter("token");
        }

        return token;
    }
    
}
